/**
 * Created by Ljh on 2016/12/7.
 */

//list页面的控制器
angular.module('listModule.controller', ['listModule.service'])
	.controller('listController', ['$scope','$stateParams','listFactory', function ($scope,$stateParams,listFactory) {
		$scope.type = $stateParams.type;
		$scope.loading = true;
		$scope.page = {
			count:5,//每页显示数量
			start:0,//请求起始项
			current:1,//当前第几页
			totalCount:0,//总记录数
			totalPage:0//总页数
		};
		//上一页
		$scope.goBack = function () {
			if( $scope.page.current <= 1){
				return;
			}
			if( $scope.page.type == 'search'){
				$scope.page.current--;
				$scope.loading = true;
				$scope.searchData( $scope.page.search,$scope.page.current );
				return false;
			}
			$scope.page.current--;
			$scope.loading = true;
			$scope.getData();
		};
		//下一页
		$scope.goForward = function () {
			if( $scope.page.current >= $scope.page.totalPage ){
				return;
			}
			if( $scope.page.type == 'search'){
				$scope.page.current++;
				$scope.loading = true;
				$scope.searchData( $scope.page.search,$scope.page.current );
				return false;
			}
			$scope.page.current++;
			$scope.loading = true;
			$scope.getData();
		};
		$scope.getData = function () {
			listFactory.getData({city:"合肥",count:5,start:(($scope.page.current-1)*$scope.page.count)},$scope.type,function (data) {
				$scope.moviesList = data;
				console.log(data);
				$scope.loading = false;
				$scope.page.totalCount = data.total;
				$scope.page.totalPage = Math.ceil( data.total/data.count );
				$scope.$apply();
			});
		};
		$scope.getData();

		//搜索功能函数
		$scope.searchData = function (search,current) {
			$scope.loading = true;
			$scope.page.current = current || 1;
			$scope.page.search = search;//供点击下一页使用
			$scope.page.type = 'search'
			listFactory.searchData({q:search,count:5,start:(($scope.page.current-1)*$scope.page.count)},$scope.page.type,function (data) {
				$scope.moviesList = data;
				console.log(data);
				$scope.loading = false;
				$scope.page.totalCount = data.total;
				$scope.page.totalPage = Math.ceil( data.total/data.count );
				console.log($scope.type);
				$scope.$apply();
			});
		};
		$scope.$emit('listToApp',$scope.searchData);

		 /*httpPromise.then(function (response) {
			$scope.moviesList = response.data;
			console.log($scope.moviesList);
		})*/
	}])
	.filter('typeFilter',function () {
		return function (input) {
			return input.map(function (v, i) {
				return v.name;
			}).join('、');
		}
	})
